package org.xiaozhou.chatgptcativen.domain.security.service.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xiaozhou.chatgptcativen.domain.security.model.vo.JwtToken;
import org.xiaozhou.chatgptcativen.domain.security.service.JwtUtil;

public class JwtRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(JwtRealm.class);

    private static JwtUtil jwtUtil = new JwtUtil();
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //校验token信息
        String jwt = (String) token.getPrincipal();
        if (jwt == null){
            throw new NullPointerException("jwtToken 不能为空");
        }
        //判断数据
        if (!jwtUtil.validate(jwt)){
            throw new UnknownAccountException();
        }
        String username = (String)jwtUtil.parseToken(jwt).get("username");
        return new SimpleAuthenticationInfo(jwt,jwt,username);
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
